<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>XHR发起GET请求</title>
</head>
<body>
  
  <script>
    // 1、创建XHR对象
    var xhr = new XMLHttpRequest();
    // 2、调用open 函数
    xhr.open('get', 'http://www.liulongbin.top:3006/api/getbooks');
    // 3、调用send函数
    xhr.send()
    // 4、监听onreadystatechange 事件
    xhr.onreadystatechange = function(){
      if(xhr.readyState === 4 && xhr.status === 200){
        // 获取服务器响应的数据
        console.log(JSON.parse(xhr.responseText));
      }
    }

  //   (function() {
  //     /**
  //      * 发一个带参数的GET请求 
  //      */
  //     var xhr = new XMLHttpRequest();
  //     xhr.open("get", "http://www.liulongbin.top:3006/api/getbooks?id=1");
  //     xhr.send();
  //     xhr.onreadystatechange = function(){
  //       if(xhr.readyState === 4 && xhr.status === 200){
  //         console.log(xhr.responseText);
  //       }
  //     }
  //   })
    var xhr2 = new XMLHttpRequest();
    xhr2.open("get", "http://www.liulongbin.top:3006/api/getbooks?id=1");
    xhr2.send();
    xhr2.onreadystatechange = function(){
      if(xhr2.readyState === 4 && xhr2.status === 200){
        console.log(JSON.parse(xhr2.responseText));
      }
    }

    /**
     * post请求
    */
    
    ;(function(){
      var xhr = new XMLHttpRequest()

      xhr.open('post', 'http://www.liulongbin.top:3006/api/addbook');
      // 设置 Content-Type 属性
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencode')
      xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社');
      xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200){
          console.log(xhr.responseText);
        }
      }
    })()

  </script>
</body>
</html>